package com.bawei.module_mine.ui

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_mine.R
import com.bawei.module_mine.model.entity.AddressEntity

class AddressAdapter(
    private var list: MutableList<AddressEntity>,
    private val onEditClick: (AddressEntity) -> Unit,
    private val onSelectClick: (AddressEntity) -> Unit
) : RecyclerView.Adapter<AddressAdapter.AddressViewHolder>() {

    private var selectedId: Long? = null

    fun setSelectedId(id: Long?) {
        selectedId = id
        notifyDataSetChanged()
    }

    fun updateData(newList: List<AddressEntity>) {
        list = newList.toMutableList()
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AddressViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_address, parent, false)
        return AddressViewHolder(view)
    }

    override fun getItemCount(): Int = list.size

    override fun onBindViewHolder(holder: AddressViewHolder, position: Int) {
        val item = list[position]
        holder.bind(item, item.id == selectedId)
        holder.ivEdit.setOnClickListener { onEditClick(item) }
        holder.ivSelected.setOnClickListener { onSelectClick(item) }
    }

    inner class AddressViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val ivSelected: ImageView = itemView.findViewById(R.id.iv_selected)
        val tvName: TextView = itemView.findViewById(R.id.tv_name)
        val tvPhone: TextView = itemView.findViewById(R.id.tv_phone)
        val tvTagDefault: TextView = itemView.findViewById(R.id.tv_tag_default)
        val tvTagType: TextView = itemView.findViewById(R.id.tv_tag_type)
        val tvAddress: TextView = itemView.findViewById(R.id.tv_address)
        val ivEdit: ImageView = itemView.findViewById(R.id.iv_edit)

        fun bind(item: AddressEntity, isSelected: Boolean) {
            tvName.text = item.receiverName ?: "-"
            tvPhone.text = item.receiverPhone?.let { maskPhone(it) } ?: "-"
            tvAddress.text = item.provinceName.orEmpty() + item.cityName.orEmpty() + item.districtName.orEmpty() + item.address.orEmpty()
            // 默认tag
            tvTagDefault.visibility = if (item.isDefault == 1) View.VISIBLE else View.GONE
            // 类型tag
            tvTagType.text = item.remark ?: "家"
            tvTagType.visibility = if (!item.remark.isNullOrEmpty()) View.VISIBLE else View.GONE
            // 选中icon
            ivSelected.setImageResource(if (isSelected) R.drawable.ic_selected else android.R.color.transparent)
        }

        private fun maskPhone(phone: String): String {
            return if (phone.length >= 7) phone.replaceRange(3, 7, "****") else phone
        }
    }
} 